#define _CRT_SECURE_NO_WARNINGS
#include "TSlist.h"

LTNode* LTInit()
{
	LTNode* phead = LTBuyNode(-1);
	assert(phead);
	return phead;
}

bool LTEmpty(LTNode* phead)
{
	assert(phead);
	return phead->next == phead;
}

LTNode* LTBuyNode(LTDataType x)
{
	LTNode* NewNode = (LTNode*)malloc(sizeof(LTNode));
	if (!NewNode)
	{
		perror("malloc fail!");
		exit(1);
	}
	NewNode->val = x;
	NewNode->next = NewNode;
	NewNode->prev = NewNode;
	return NewNode;
}
void LTPrint(LTNode* phead)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->val);
		pcur = pcur->next;
	}
	printf("\n");
}

void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* NewNode = LTBuyNode(x);
	NewNode->next = phead->next;
	NewNode->prev = phead;

	phead->next->prev = NewNode;
	phead->next = NewNode;
}


void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* NewNode = LTBuyNode(x);
	NewNode->next = phead;
	NewNode->prev = phead->prev;

	phead->prev->next = NewNode;
	phead->prev = NewNode;
}

void LTPopFront(LTNode* phead)
{
	assert(!LTEmpty(phead));
	LTNode* del = phead->next;
	del->next->prev = del->prev;
	del->prev->next = del->next;
	free(del);
	del = NULL;
}

void LTPopBack(LTNode* phead)
{
	assert(!LTEmpty(phead));
	LTNode* del = phead->prev;
	del->prev->next = del->next;
	del->next->prev = del->prev;
	free(del);
	del = NULL;
}

LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->val == x)
			return pcur;
		pcur = pcur->next;
	}
	return NULL;
}

void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	LTNode* NewNode = LTBuyNode(x);

	NewNode->prev = pos;
	NewNode->next = pos->next;
	pos->next->prev = NewNode;
	pos->next = NewNode;
}

void LTErase(LTNode* pos)
{
	assert(pos);
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	free(pos);
	pos = NULL;
}

void LTDestroy(LTNode* phead)
{
	assert(phead);
	LTNode* pcur = phead;
	while (pcur->next != phead)
	{
		pcur = pcur->next;
		free(pcur->prev);
	}
	free(pcur);
	phead = NULL;
}